//
//  UserAreaController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/4/22.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "UserAreaController.h"
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import "HZAreaPickerView.h"

@interface UserAreaController ()<CLLocationManagerDelegate,HZAreaPickerDelegate>
@property (strong, nonatomic) IBOutlet UILabel *addressLabel;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLGeocoder *gecoder;
@property (strong, nonatomic) HZAreaPickerView *locatePicker;


@end

@implementation UserAreaController
- (CLLocationManager *) locationManager {
    if (_locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc]init];
    }
    return _locationManager;
}

- (CLGeocoder *)gecoder {
    if (_gecoder == nil) {
        self.gecoder = [[CLGeocoder alloc]init];
    }
    return _gecoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"地区";
    __weak typeof(self)weakSelf = self;
    [self addLeftButtonWithImage:[UIImage imageNamed:@"返回箭头"] actionBlock:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    [self addRightButtonWithTitle:@"完成" actionBlock:^{
        if ([weakSelf.addressLabel.text isEqualToString:@"正在获取您的位置..."]) {
            [SVProgressHUD showErrorWithStatus:@"请重新选择您的位置"];
            
        } else {
            [weakSelf web_requestChangeArea];
        }
    }];
    [self locationSetting];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addressLabelAction:) name:@"addressStr" object:nil];
}

- (void)web_requestChangeArea
{
    NSString *uidStr = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultsUserIdKey];
    NSDictionary *dict =  @{@"uid" : uidStr,@"param" : @"city",@"value" : self.addressLabel.text};
    __weak typeof(self)weakSelf = self;
    [HttpRequestManager getMethod:KChangeUserInfoInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            [[NSUserDefaults standardUserDefaults] setObject:self.addressLabel.text forKey:KUserDefaultArea];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:@"失败"];
        }
    }];
}

- (void)addressLabelAction:(NSNotification *)sender {
    self.addressLabel.text = sender.object;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// 重新选择区域
- (IBAction)areaAddressButton:(id)sender {
    [self cancelLocatePicker];
    self.locatePicker = [[HZAreaPickerView alloc] initWithStyle:HZAreaPickerWithStateAndCityAndDistrict delegate:self];
    [self.locatePicker showInView:self.view];
}

#pragma mark - HZAreaPicker delegate
-(void)pickerDidChaneStatus:(HZAreaPickerView *)picker
{
    if (picker.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        self.addressLabel.text = [NSString stringWithFormat:@"%@ %@ %@", picker.locate.state, picker.locate.city, picker.locate.district];
    }
}

-(void)cancelLocatePicker
{
    [self.locatePicker cancelPicker];
    self.locatePicker.delegate = nil;
    self.locatePicker = nil;
}

#pragma mark -----定位到当前所在城市 ------
- (void)locationSetting {
    //检测定位服务是否打开
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务尚未打开");
        return;
    }
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        //必须写一下代码:requestWhenInUseAuthorization或者是 requestAlwaysAuthorization, 在使用之前需要先调用这个方法
        [self.locationManager requestWhenInUseAuthorization];
        //  设置代理
        _locationManager.delegate = self;
        // 设置定位精度
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 地位频率，每隔多少米定位一次
        CLLocationDistance  distance = 10.0;
        _locationManager.distanceFilter = distance;
        // 启动跟踪
        [_locationManager startUpdatingLocation];
    }
}

#pragma mark ---定位delegate---
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    // 数组里面存放的是CLLocation对象，一个CLLocation代表一个位置
    CLLocation *location = [locations lastObject];
    [self getCityByCoordinate:location];
    [manager stopUpdatingLocation];
}

//当定位失败的时候触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        // 访问拒绝
        [self alertViewShowWithMessage:@"访问地理位置被拒绝"];
    } if ([error code] == kCLErrorLocationUnknown) {
        
        [self alertViewShowWithMessage:@"无法获取地理位置"];
    }
}

#pragma mark --- 反地理编码 ---
- (void)getCityByCoordinate:(CLLocation *)location {
    [self.gecoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placeMark = [placemarks firstObject];
        NSLog(@"%@--%@--%@",placeMark.administrativeArea,placeMark.locality,placeMark.subLocality);
        self.addressLabel.text = [NSString stringWithFormat:@"%@ %@ %@",placeMark.administrativeArea,placeMark.locality,placeMark.subLocality];
    }];
}

#pragma mark - 警告视图
- (void)alertViewShowWithMessage:(NSString *)message {
    //    [[[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil]show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
